package com.aiden.app.common.util

import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.support.v7.app.AlertDialog

object NoticeDialog {
    private var dialog: AlertDialog? = null

    fun alert(context: Context, message: String, title: String = "提示", positiveText: String = "确定",
              positiveTextColor: Int = Color.parseColor("#2dbefe"), onPositiveClickListener: DialogInterface.OnClickListener = DialogInterface.OnClickListener { dialog, which -> dialog?.cancel() }, cancelable: Boolean = true) {

        if (dialog == null || !(dialog?.isShowing!!)) {
            val builder = AlertDialog.Builder(context)
            builder.setTitle(title)
                    .setMessage(message)
                    .setPositiveButton(positiveText, onPositiveClickListener)
                    .setCancelable(cancelable)
            dialog = builder.create()
            dialog?.show()
            dialog?.getButton(AlertDialog.BUTTON_POSITIVE)?.setTextColor(positiveTextColor)
        }
    }

    fun confirm(context: Context, message: String, title: String = "",
                positiveText: String = "确定", positiveTextColor: Int = Color.parseColor("#2dbefe"),
                onPositiveClickListener: DialogInterface.OnClickListener = DialogInterface.OnClickListener { dialog, which -> dialog?.cancel() },
                negativeText: String = "取消", negativeTextColor: Int = Color.parseColor("#666666"),
                onNegativeClickListener: DialogInterface.OnClickListener = DialogInterface.OnClickListener { dialog, which -> dialog?.cancel() },
                onCancelListener: DialogInterface.OnCancelListener = DialogInterface.OnCancelListener { }) {

        if (dialog != null && dialog?.isShowing!!) {
            dialog?.let {
                if (it.window.decorView.isAttachedToWindow) {
                    it.setTitle(title)
                    it.setMessage(message)
                    it.setButton(DialogInterface.BUTTON_POSITIVE, positiveText, onPositiveClickListener)
                    it.setButton(DialogInterface.BUTTON_NEGATIVE, negativeText, onNegativeClickListener)
                }
            }
        } else {
            val builder = AlertDialog.Builder(context)
            builder.setTitle(title)
                    .setMessage(message)
                    .setPositiveButton(positiveText, onPositiveClickListener)
                    .setNegativeButton(negativeText, onNegativeClickListener)
            dialog = builder.create()
            dialog?.setOnCancelListener(onCancelListener)
            dialog?.show()
            dialog?.getButton(AlertDialog.BUTTON_POSITIVE)?.setTextColor(positiveTextColor)
            dialog?.getButton(AlertDialog.BUTTON_NEGATIVE)?.setTextColor(negativeTextColor)
        }
    }

    fun show() {
        if (dialog != null && !dialog?.isShowing!!) {
            dialog?.show()
        }
    }
}